/**
 * 锁屏
 */
import { Message } from 'element-ui'
import Cookies from 'js-cookie'
const whiteList = ['/login/navigation', '/login', '/password', '/register', '/helpDocs/index']
import router from '@/router'
const defaultSettings = require('@/settings.js')

router.beforeEach(async(to, from, next) => {
  var islockScreen = Cookies.get('lockScreen')
  if (islockScreen && islockScreen === 'true') {
    if (to.name === 'lockScreen' || to.name === 'password') {
      next()
    } else {
      Message({
        message: '屏幕已被锁定,请输入密码进行解锁!',
        type: 'warning',
        duration: 3 * 1000
      })
      next(`/lockScreen?redirect=${to.path}`)
    }
  } else {
    next()
  }
})

let lastTime = new Date().getTime()
let currentTime = new Date().getTime()
const timeOut = defaultSettings.lockScreen * 60 * 1000 // 设置超时时间
var flag = null

flag = window.setInterval(checkTimeout, 1000 * 15)

window.onload = function() {
  Cookies.set('lastTime', new Date().getTime())
  window.document.onmousedown = function() {
    Cookies.set('lastTime', new Date().getTime())
  }
}

function checkTimeout() {
  currentTime = new Date().getTime() // 更新当前时间
  lastTime = Cookies.get('lastTime')
  if (currentTime - lastTime > timeOut) { // 判断是否超时
    if (whiteList.indexOf(router.currentRoute.path) === -1) {
      Cookies.remove()
      Cookies.set('lockScreen', true)
      router.push({ path: '/lockScreen' })
    }
    clearInterval(flag)
  }
}
